import { login, logout, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import router, { resetRouter } from '@/router'

var userNotices = []
try {
  if (localStorage.userNotices) {
    userNotices = localStorage.getItem('userNotices')
  }
} catch (e) { console.log(e) }
const state = {
  token: getToken(),
  name: '',
  avatar: '',
  introduction: '',
  roles: [],
  userNotices: userNotices // 用户通知信息
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_INTRODUCTION: (state, introduction) => {
    state.introduction = introduction
  },
  SET_NAME: (state, name) => {
    state.name = name
    // console.log(11)
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  // 更新用户通知信息
  SET_USER_NOTICES: (state, data) => {
    // state.userNotices = data
    try {
      state.userNotices = data
      localStorage.userNotices = data
      console.log('用户通知信息commit===')
    } catch (e) {
      console.log(e)
    }
  }
}

const actions = {
  // 清楚用户通知信息
  clearNotice({ commit }) {
    commit('SET_USER_NOTICES', [])
    localStorage.removeItem('userNotices')
  },
  // 用户通知信息 此方法已弃用 直接存缓存
  userNotcie({ commit }, data) {
    commit('SET_USER_NOTICES', JSON.stringify(data))
  },

  // user login
  login({ commit }, userInfo) {
    const { username, password, verifyCode } = userInfo
    return new Promise((resolve, reject) => {
      // eslint-disable-next-line no-undef
      login({ userName: username.trim(), password: password, verifyCode: verifyCode }).then(response => {
        // const { data } = response
        // commit('SET_TOKEN', data.token)
        // setToken(data.token)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      // console.log(state.token)
      getInfo(state.token).then(response => {
        const { data } = response
        // console.log(response)
        if (response.code !== 200) {
          reject(response)
        }

        // const { roles, name, avatar, introduction } = data

        // roles must be a non-empty array
        // if (!roles || roles.length <= 0) {
        //   reject('getInfo: roles must be a non-null array!')
        // }
        commit('SET_TOKEN', data.info)
        setToken(data.info)
        commit('SET_ROLES', data.permissions)
        commit('SET_NAME', data.loginNo)
        commit('SET_AVATAR', 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif')
        commit('SET_INTRODUCTION', data.realName)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        commit('SET_TOKEN', '')
        commit('SET_ROLES', [])
        removeToken()
        resetRouter()
        dispatch('clearNotice')

        // reset visited views and cached views
        // to fixed https://github.com/PanJiaChen/vue-element-admin/issues/2485
        dispatch('tagsView/delAllViews', null, { root: true })
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      removeToken()
      resolve()
    })
  },

  // dynamically modify permissions
  changeRoles({ commit, dispatch }, role) {
    return new Promise(async resolve => {
      const token = role + '-token'
      commit('SET_TOKEN', token)
      setToken(token)

      const { roles } = await dispatch('getInfo')

      resetRouter()

      // generate accessible routes map based on roles
      const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true })

      // dynamically add accessible routes
      router.addRoutes(accessRoutes)

      // reset visited views and cached views
      dispatch('tagsView/delAllViews', null, { root: true })
      dispatch('clearNotice')

      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
